import { createSlice } from "@reduxjs/toolkit";

export const counterSlice = createSlice({
  name: "counter",
  initialState: {
    cart: {money:0,items:[]}
  },
  reducers: {
    increment: (state) => {
      state.card += 1;
    },
    decrement: (state) => {
      state.cart -= 1;
    },
    incrementByAmount: (state, action) => {
      state.cart += action.payload;
    },
    add:(state,action)=>{
        let item = action.payload
        item.count=1 
        console.log(item)
        let index = state.cart.items.findIndex((i)=>i.id==item.id)
        if(index==-1){
            state.cart.items.push(item)
        }else{
            state.cart.items[index].count+=1
        }
        state.cart.money+=item.price
    },
    remove:(state,action)=>{
        let item = action.payload
        item.count=1 
        console.log(item)
        let index = state.cart.items.findIndex((i)=>i.id==item.id)
        console.log(index)
        if(index==-1){
            state.cart.items.pop()
        }else{
            state.cart.items[index].count-=1
            if(state.cart.items[index].count==0){
                state.cart.items.splice(index,1)
              }
        }
        state.cart.money-=item.price
    }
  }
});

// Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount,add ,remove} = counterSlice.actions;

export default counterSlice.reducer;
